<template>
<div>
  <main-header></main-header>
  <div class="row" style="margin-top: 80px ">
    <div class="col-lg-12">
      <div class="section-top text-center">
        <h2>Manage personal information</h2>
        <p>安全，便捷，修改</p>
      </div>
    </div>
  </div>
  <div class="container">
    <div style="padding-top: 80px">
    <el-tabs tab-position="left">
      <el-tab-pane label="个人信息">
        <div class="row">
          <div class="col-md-7">
            <h3> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;编辑个人信息</h3>
            <el-form :model="ruleForm" :rules="rules" ref="ruleFormRefs" label-width="80px" class="demo-ruleForm">
              <el-form-item label="昵称" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
              </el-form-item>
              <el-form-item label="手机号" >
                <el-input v-model="ruleForm.mobilephone" disabled></el-input>
              </el-form-item>
              <el-form-item label="性别">
                <el-radio-group v-model="ruleForm.sex">
                  <el-radio label="男"></el-radio>
                  <el-radio label="女"></el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="学校" prop="school">
                <el-input v-model="ruleForm.school"></el-input>
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                <el-input v-model="ruleForm.email"></el-input>
              </el-form-item>
              <el-form-item label="注册时间" >
                <el-input v-model="ruleForm.createtime" disabled></el-input>
              </el-form-item>
              <el-form-item label="简介" prop="sign">
                <el-input  type="textarea" v-model="ruleForm.sign"></el-input>
              </el-form-item>
              <el-form-item style="text-align: center">
                <el-button type="danger" @click="onSubmitInfo">保存</el-button>
              </el-form-item>
            </el-form>
          </div>
          <div class="col-md-3">
            <div class="avatar">
              <div class="imgContainer">
                <img :src="ruleForm.uimage" alt="头像" style="width: 150px;border-radius: 50%">
              </div>
              <el-upload
                :action="ossUrl"
                :on-success="handleAvatarSuccess"
              >
                <el-button size="small" type="primary" style="margin-top: 5px">上传头像</el-button>
              </el-upload>
            </div>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="销售记录" style="padding: 20px">
        <h3 style="margin-bottom: 20px">&nbsp;&nbsp;&nbsp;&nbsp;管理销售记录</h3>
        <el-table
          :data="sellRecord"
          stripe
          style="width: 100%">
          <el-table-column  label="商品名称" width="180"> <template slot-scope="scope">{{ scope.row.commname }}</template></el-table-column>
          <el-table-column prop="commdesc" label="商品简介" width="180"></el-table-column>
          <el-table-column prop="soldtime" label="销售时间" width="180"></el-table-column>
          <el-table-column label="成交价格"> <template slot-scope="scope"><el-tag type="warning">{{ scope.row.thinkmoney }}</el-tag></template></el-table-column>
          <el-table-column label="操作"> <template slot-scope="scope">
            <el-button type="danger" plain @click="deleteItem(scope.row.id)">删除记录</el-button>
          </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
    </div>

  </div>
  <main-footer></main-footer>
</div>
</template>

<script>
import MainHeader from '../pages/Home/header'
import MainFooter from '../pages/Home/footer'
import {baseUrl, ossUrl} from '../utils/Address'
export default {
  mounted () {
    this.userid = window.localStorage.getItem('userId')
    this.getuserInfo()
    this.getSoldRecord()
    this.getAuth()
  },
  name: 'myInfo',
  components:{
    MainHeader,
    MainFooter
  },
  data(){
    var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    var validateEmail=(rule,value,callback)=>{
      if (value === '') {
        callback();
      } else if(!reg.test(value)){
        callback(new Error('邮箱格式不正确！'));
       }
      };
  return{
    ossUrl:ossUrl,
    userid:'',
    auth:{},
    sellRecord:[],
    ruleForm:{},
    rules:{
      username:[
         { required: true, message: '请输入用户名', trigger: 'blur' },
      ],
      school:[
         { required: true, message: '请输入学校', trigger: 'blur' },
      ],
      email:[
         { validator: validateEmail, trigger: 'blur' },
        { required: true, message: '请输入学校', trigger: 'blur' },
      ]
    }
   }
  },
  methods: {
    get_suffix (filename) {
      let pos = filename.lastIndexOf('.')
      let suffix = ''
      if (pos != -1) {
        suffix = filename.substring(pos)
      }
      return suffix
    },
    random_string (len) {
      len = len || 32
      var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      var maxPos = chars.length
      var pwd = ''
      for (let i = 0; i < len; i++) {
        pwd += chars.charAt(Math.floor(Math.random() * maxPos))
      }
      return pwd
    },
    getuserInfo () {
      this.axios.get(`${baseUrl}/user/userinfo/${this.userid}`).then(
        res => {
          this.ruleForm=res.data.data
          console.log(this.ruleForm.uimage)
        }
      )
    },
    async  getSoldRecord(){
       let data = await this.axios.get(`${baseUrl}/soldrecord/lookuser`)
       this.sellRecord=data.data.data
       console.log(this.sellRecord)
    },
    async getAuth () {
      let res = await this.axios.post('http://49.234.32.190:8081/oss/policy')
      this.auth = res.data
    },
    onSubmitInfo(){
         this.axios.post(`${baseUrl}/user/updateinfo`,this.ruleForm).then(
           res=>{
             if(res.data.status!==200){
               this.$message.error(res.data.message)
               window.localStorage.setItem('username', this.ruleForm.username)
             }else{
               this.$message.success('修改成功')
             }
           }
         ).catch(err=>{
           console.log(err)
         })
    },
    handleAvatarSuccess (res,file) {
      console.log(file)
      var ossData = new FormData()
      ossData.append('name', file.name)
      let filename = file.name
      let picName = this.random_string(10) + this.get_suffix(filename)
      let keyValue = this.auth.dir + picName
      ossData.append('key', keyValue)
      ossData.append('policy', this.auth.policy)
      ossData.append('OSSAccessKeyId', this.auth.accessid)
      ossData.append('success_action_status', 200)
      ossData.append('signature', this.auth.signature)
      ossData.append('file', file.raw, file.name)
      this.axios.post('http://second-shop.oss-cn-shanghai.aliyuncs.com', ossData, {
          withCredentials: false,
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        }).then(res => {
        if (res.status === 200) {
          let uimage = 'http://' + this.auth.host + '/' + keyValue
          console.log(uimage)
          if(uimage!==null){
            this.axios.post(`${baseUrl}/user/updateuimg`,{uimage}, {
                headers: {
                  'content-type': 'application/json'
                }
              }
            ).then(
              res=>{
                console.log(res)
                this.getuserInfo()
              }
            )
          }
        }
      })
        .catch(error => {
          console.log(error)
        })
    },
    deleteItem(id){
      this.axios.put(`${baseUrl}/soldrecord/delect/${id}`).then(
        res=>{
         if(res.data.message==='删除记录成功'){
           this.$message.success('删除记录成功')
           this.getSoldRecord()
         }else {
           this.$message.error('删除记录失败')
        }}
      ).catch(err=>{
        console.log(err)
        this.$message.error('删除记录失败')
      })
    }
  }
}
</script>

<style scoped>
.avatar{
  display: flex;
  margin-top: 150px;
  flex-direction: column;
  align-items: center;
}
.container{
  min-height: 800px;
  background-color: #f0f1f3;
}
.demo-ruleForm{
  max-width: 500px;
  padding: 30px;
}
</style>
